package com.ggkt.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * <p>
 * http 请求工具类
 * </p>
 * 
 * @author ggkt
 */
public class HttpUtil {

	public static Log log = LogFactory.getLog(HttpUtil.class);
	private static RequestConfig defaultRequestConfig = RequestConfig.custom()
			.setSocketTimeout(1000 * 60 * 2)
			.setConnectTimeout(1000 * 60 * 2)
			.setConnectionRequestTimeout(1000 * 60 * 2)
			.build();
    public static void deleteCookie(HttpServletResponse response, String name){
        setCookie(response, null, name, null, 0, "/");
    }
    
    public static void deleteCookie(HttpServletResponse response, String domian, String name){
        setCookie(response, domian, name, null, 0, "/");
    }
	
	public static void setCookie(HttpServletResponse response, String name, String value, String uri){
		
		setCookie(response, null, name, value, -1, uri);
	}
	
	public static void setCookie(HttpServletResponse response, String name, String value, int expiry, String uri){
		
		setCookie(response, null, name, value, expiry, uri);
	}
	
	public static void setCookie(HttpServletResponse response, String domian, String name, String value, int expiry, String uri){
		
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(expiry);
		cookie.setPath(uri);
		if(domian != null){
			cookie.setDomain(domian);
		}
		response.addCookie(cookie);
	}
	
	/**
	 * 获取cookie
	 * 
	 * @param request
	 * @return 返回形如：utype=3;JSESSIONID=8102B6B220C6C3282E8635F63A797927
	 */
	public static String getCookie(HttpServletRequest request){
		
		StringBuffer cookieString = new StringBuffer();
		Cookie[] cookies = request.getCookies();
	    if(cookies != null){
	    	Cookie c = null;
	    	for (int i = 0; i < cookies.length; i++ ) {
	    		c = cookies[i];
	    		if(i > 0){
	    			cookieString.append("&");
	    		}
	    		cookieString.append(c.getName()).append("=").append(c.getValue());
			}
	    }
	    
		return cookieString.toString();
	}
	
	/**
	 * 根据名字获取cookie变量值
	 * 
	 * @param request
	 * @param name cookie名字
	 */
	public static String getCookie(HttpServletRequest request, String name){
		
		Map<String,Cookie> cookieMap = ReadCookieMap(request);
		Cookie cookie = null;
		if(cookieMap.containsKey(name)){
			cookie = (Cookie)cookieMap.get(name);
		}  
		
		return cookie != null ? cookie.getValue() : "";
	}
	
	/**
	 * 将cookie封装到Map里面
	 */
	private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){ 
		
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(cookies != null){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    
	    return cookieMap;
	}

	public static String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		//解决多次代理多个ip的问题
		if(StringUtils.isNotBlank(ip) && ip.indexOf(",")>-1){
			ip = ip.substring(0,ip.indexOf(","));
		}
		log.info("getIpAddr, ip:" + ip);
		return ip;
	}
	
	public static void send_nocache_header(HttpServletResponse response) {

		response.setHeader("Expires", " Mon, 26 Jul 1970 05:00:00 GMT");
		response.setHeader("Last-Modified", new Date() + " GMT");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setHeader("Pragma", "no-cache");
	}

	/**
	 * 发出http post请求(UTF-8编码)
	 * 
	 * @param serverURL
	 *            请求路径
	 */
	public static String httpPost(String serverURL, String param) {

		return httpPost(null, serverURL, param, "UTF-8",null);
	}

	/**
	 * 发出http post请求
	 * 
	 * @param serverURL
	 *            请求路径
	 * @param codeType
	 *            字符串编码格式，形式:GBK
	 */
	public static String httpPost(String serverURL, String param,
			String codeType) {

		return httpPost(null, serverURL, param, codeType,null);
	}

	/**
	 * 发出http post请求
	 * 
	 * @param serverURL
	 *            请求路径
	 * @param paramStr
	 *            请求参数，形式:userName=aaa&password=bbb
	 * @param codeType
	 *            字符串编码格式，形式:GBK
	 * @param referer
	 *            请求headerd的referer
	 */
	public static String httpPost(String referer, String serverURL,
			String paramStr, String codeType ,String ip) {

		HttpClient httpClient = new DefaultHttpClient();
		// httpPost.setHeader("X-Forwarded-For", "172.31.29.119"); //本地测试时打开
		httpClient.getParams()
				.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000)
				.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);

		HttpPost httpPost = new HttpPost(serverURL);
		if(ip != null){
			httpPost.setHeader("X-Forwarded-For", ip);
		}
		if (referer != null) {
			httpPost.setHeader("referer", referer);
		}
		BufferedReader br = null;
		StringBuffer backData = new StringBuffer();
		try {
			// 请求参数等处理
			StringEntity paramEntity = new StringEntity(paramStr, codeType);
			paramEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(paramEntity);
			
			// 发出请求
			HttpResponse httpResponse = httpClient.execute(httpPost);
			
			// 开始解析响应
			HttpEntity responseEntity = httpResponse.getEntity();
			br = new BufferedReader(new InputStreamReader(
					responseEntity.getContent(), codeType));
			String line = null;
			while ((line = br.readLine()) != null) {
				backData.append(line);
			}
			
			if (responseEntity != null) {
				responseEntity.consumeContent();
			}
		} catch (Exception e) {
			
			log.error("httpPost error! params: referer = " + referer 
					+ " ,serverURL = " + serverURL + " ,paramStr = " + paramStr + " ,codeType = " + codeType, e); 
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (Exception e) {
				}
			}
		}

		log.info("post to :" + serverURL + ", params is :" + paramStr
				+ " back data is : " + backData);

		return backData.toString(); // 返回结果
	}

	public static String post(String serverURL, Map<String, Object> params, Map<String, String> headers){

		StringBuffer paramStr = new StringBuffer();

		for (String key : params.keySet()) {
			paramStr.append(key).append("=").append(params.get(key)).append("&");
		}

		return post(serverURL, paramStr.toString(), "UTF-8", headers);

	}

	//自定义header的post请求
	public static String post(String serverURL, String paramStr, String codeType, Map<String, String> headers) {

		HttpClient httpClient = new DefaultHttpClient();
		// httpPost.setHeader("X-Forwarded-For", "172.31.29.119"); //本地测试时打开
		httpClient.getParams()
				.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000)
				.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);

		HttpPost httpPost = new HttpPost(serverURL);
		for(Map.Entry<String, String> map : headers.entrySet()){
			httpPost.addHeader(map.getKey(),map.getValue());
		}
		BufferedReader br = null;
		StringBuffer backData = new StringBuffer();
		try {
			// 请求参数等处理
			StringEntity paramEntity = new StringEntity(paramStr, codeType);
			paramEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(paramEntity);

			// 发出请求
			HttpResponse httpResponse = httpClient.execute(httpPost);

			// 开始解析响应
			HttpEntity responseEntity = httpResponse.getEntity();
			br = new BufferedReader(new InputStreamReader(
					responseEntity.getContent(), codeType));
			String line = null;
			while ((line = br.readLine()) != null) {
				backData.append(line);
			}

			if (responseEntity != null) {
				responseEntity.consumeContent();
			}
		} catch (Exception e) {

			log.error("httpPost error! params: serverURL = " + serverURL + " ,paramStr = " + paramStr + " ,codeType = " + codeType, e);
		}finally{
			if(br!=null){
				try {
					br.close();
				} catch (Exception e) {
				}
			}
		}

		log.info("post to :" + serverURL + ", params is :" + paramStr
				+ " back data is : " + backData);

		return backData.toString(); // 返回结果
	}


	public static String httpPostJson(String serverURL, String param, String encoding) {
        String strBack = null;
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        StringEntity stringEntity = null;
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        BufferedReader br = null;
        
        try{
            httpClient = new DefaultHttpClient();
            httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, 10000)
                                                         .setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
            httpPost = new HttpPost(serverURL);

            stringEntity = new StringEntity(param, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            br = new BufferedReader(new InputStreamReader(httpEntity.getContent(),encoding));
            StringBuffer backData = new StringBuffer();
            String line = null;
            while((line = br.readLine())!=null){
                backData.append(line);
            } 
            strBack = backData.toString();
            log.debug("---> post to: "+serverURL);
            log.debug("---> data is: "+param);
            log.debug("---> back data is: "+backData);
            if(httpEntity != null) {
				httpEntity.consumeContent();
			}
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //1.关闭BufferedReader
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //2.关闭StringEntity
            stringEntity = null;
            //3.关闭HttpEntity
            if(httpEntity != null){
                try {
                    httpEntity.consumeContent();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //4.关闭HttpResponse
            httpResponse = null;
            //5.释放HttpPost
            if(httpPost != null){
                httpPost.abort();
			}
            //6.关闭HttpClient
            if(httpClient != null){
                httpClient.getConnectionManager().shutdown();
			}
        }
        return strBack;
    }

	public static String sendGet(String url, String param,String token) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			System.out.println(urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			if (token!=null){
				// 设置通用的请求属性
				connection.setRequestProperty("Access-Token",token);
			}
			connection.setConnectTimeout(5000);
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String httpGet(String serverURL, String codeType, Map<String, String> headerMap) {
		BufferedReader in = null;
		String content = null;
		CloseableHttpClient client=null;
		CloseableHttpResponse httpResponse = null;
		HttpGet request = null;
		try {
			// 定义HttpClient
			client = HttpConnectionManager.getHttpClient();

			URL url = new URL(serverURL);
			URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);

			request = new HttpGet(uri);

			request.setConfig(defaultRequestConfig);
			if (headerMap != null ) {
				for(Map.Entry<String, String> entry : headerMap.entrySet()){
					request.setHeader(entry.getKey(), entry.getValue());
				}
			}

			httpResponse = client.execute(request);

			if (httpResponse.getStatusLine ().getStatusCode () != 200) {
				request.abort();
				return null;
			}
			in = new BufferedReader(new InputStreamReader(httpResponse.getEntity()
					.getContent(), codeType));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			content = sb.toString();
		} catch (Exception e) {
			log.error("httpGet error! serverURL = " + serverURL
					+ ", error msg = " + (e != null ? e.getMessage() : ""));
			request.abort();
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					log.error("finally close httpClient", e);
				}
			}

			if(httpResponse != null){
				try {
					httpResponse.close();
				} catch (IOException e) {
					log.error("finally close httpClient", e);
				}
			}

			if(client != null){
				try {
					client.close();
				} catch (IOException e) {
					log.error("finally close httpClient", e);
				}
			}
		}

		return content;
	}
	/**
	 * 发出http get请求
	 * 
	 * @param serverURL
	 *            请求路径(带参数)
	 */
	public static String httpGet(String serverURL) {

		return httpGet(serverURL, "UTF-8");
	}

	/**
	 * 发出http get请求
	 * 
	 * @param serverURL
	 *            请求路径(带参数)
	 * @param codeType
	 *            字符串编码格式，形式:GBK
	 */
	public static String httpGet(String serverURL, String codeType) {

		return httpGet(serverURL, codeType, "");
	}
	/**
	 * 发出http get请求
	 * 
	 * @param serverURL
	 *            请求路径(带参数)
	 * @param codeType
	 *            字符串编码格式，形式:GBK
	 * @param cookie
	 * 			cookie参数字符串，形式：utype=3;JSESSIONID=8102B6B220C6C3282E8635F63A797927; 
	 */
	public static String httpGet(String serverURL, String codeType, String cookie) {
		
		BufferedReader in = null;
		String content = null;
		try {
			// 定义HttpClient
			HttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpGet request = new HttpGet();
			
			URL url = new URL(serverURL);
			URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
					url.getQuery(), null);
			request.setURI(uri);
			if(StringUtils.isNotBlank(cookie)){
				request.setHeader("cookie", cookie);
			}
			
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent(), codeType));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			content = sb.toString();
			log.info("get url:" + uri + ", result:" + content + ", cookie:" + cookie);
		} catch (Exception e) {
			
			log.error("URL=" + serverURL, e);
		} finally {
			if (in != null) {
				try {
					in.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return content;
	}
	
	/**
	 * 根据客户端 User Agent Strings 判断其浏览器内核类型
	 * 
	 * @param userAgent
	 * 
	 * @return "chrome"，"firefox"，"ie"
	 */
	public static String getBrowserType(String userAgent) {
		
		if(StringUtils.isBlank(userAgent)){
			return "other";
		}

		userAgent = userAgent.toLowerCase();

		if (userAgent.contains("chrome")) {

			return "chrome";
		} else if (userAgent.contains("firefox")) {

			return "firefox";
		} else if (userAgent.contains("msie")) {

			return "ie";
		}

		return "other";
	}
	
	//是否频繁操作
	public static boolean isContinual(HttpSession session){
		long now = System.currentTimeMillis();
		Object last = session.getAttribute("lastOperateTimeLong");
		session.setAttribute("lastOperateTimeLong", now);
		if(last != null){
			long lastOperateTime = Long.parseLong(last.toString());
			if(now - lastOperateTime < 1000){
				return true;
			}
		}
		return false;
	}
	
	public static void main1(String[] args) {
		DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate theendDate = LocalDate.of(2020, 7, 15);
		LocalDate day = LocalDate.of(2020, 6, 5);
		do {
			String result = HttpUtil.httpGet("http://mcsms.ggkt.com/console/reports/updateSemCostUtmDatas?"
					+ "startDate="+ day.format(dayFormatter) 
					+ "&endDate=" + day.format(dayFormatter) );
			System.out.println(result);
			day = day.plusDays(1);
		} while(day.compareTo(theendDate) < 0);
		
	}

}